/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UsuarioChat.java
 *
 * Created on 02/11/2008, 14:05:30
 */
package br.unifor.redes1.odirabel.gui.client;

import br.unifor.redes1.odirabel.gui.server.Cliente;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author pedro
 */
public class UsuarioChat extends javax.swing.JPanel implements Runnable {

    private Cliente cliente;
    private Socket serverSocket;
    private BufferedReader input;
    private PrintWriter output;
    private String userInput;
    private String[] vetor;
    private String resposta;
    private String text;
    private String login;
    private String nomeArq;
    private String transmissor;
    private boolean modoReceptorArquivo;
    private InputStream inputStream;
    private OutputStream outputStream;
    public static final int BUFFER_LEITURA = 4096;
    private FileOutputStream arquivoQueEstaChegando;

    /** Creates new form UsuarioChat */
    public UsuarioChat(String login, Cliente cliente, Socket socket) {
        try {
            initComponents();
            this.cliente = cliente;
            serverSocket = socket;
            this.login = login;
            input = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
            inputStream = socket.getInputStream();
            output = new PrintWriter(serverSocket.getOutputStream(), true);
            outputStream = socket.getOutputStream();
            modoReceptorArquivo = false;
        } catch (IOException ex) {
            JOptionPane.showConfirmDialog(null, ex.getMessage());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jButton3 = new javax.swing.JButton();

        jButton1.setText("Enviar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        setLayout(new java.awt.BorderLayout());

        jSplitPane1.setDividerLocation(300);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jPanel1.setLayout(new java.awt.BorderLayout());
        jPanel1.add(jTextField1, java.awt.BorderLayout.CENTER);

        jButton2.setText("Enviar Mensagem");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2, java.awt.BorderLayout.LINE_END);

        jSplitPane1.setRightComponent(jPanel1);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jButton3.setText("Enviar Arquivo");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton3);

        jPanel2.add(jPanel3, java.awt.BorderLayout.PAGE_START);

        jSplitPane1.setLeftComponent(jPanel2);

        add(jSplitPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        text = jTextField1.getText();
        output.println("MESSAGE " + login + ":" + text);
        output.flush();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        jButton2.setEnabled(Boolean.TRUE);
        JFileChooser jFile = new JFileChooser();
        int returnVal = jFile.showOpenDialog(null);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            modoArquivo();
            final File file = jFile.getSelectedFile();
            new Thread() {

                public void run() {
                    byte[] bufferLeituraArquivo = new byte[UsuarioChat.BUFFER_LEITURA];
                    try {
                        FileInputStream fIS = null;
                        output.println("FILE " + file.getName() + ":" + login);
                        output.flush();
                        //outputStream.flush();
                        fIS = new FileInputStream(file);

                        int bytesLidos = 0;
                        while ((bytesLidos = fIS.read(bufferLeituraArquivo)) != -1) {
                            jTextArea1.append("Enviando arquivo..\nPor favor abra uma nova janela para iniciar uma nova conversa.");
                            jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getMaximum());
                            outputStream.write(bufferLeituraArquivo, 0, bytesLidos);

                        }
                        //modoTexto();
                        fIS.close();
                        JOptionPane.showMessageDialog(null, "O arquivo foi enviado.");
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(UsuarioChat.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(UsuarioChat.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }.start();
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

    @Override
    public void run() {
        while (Boolean.TRUE) {
            try {
                if (!modoReceptorArquivo) {
                    userInput = input.readLine();
                    tryMsg(userInput);
                } else {
                    int bytesLidos = 0;
                    byte[] bufferLeitura = new byte[UsuarioChat.BUFFER_LEITURA];
                    while ((bytesLidos = inputStream.read(bufferLeitura)) != -1) {
                        jTextArea1.append("Recebendo arquivo..\n");
                        jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getMaximum());
                        arquivoQueEstaChegando.write(bufferLeitura, 0, bytesLidos);
                    }
                    arquivoQueEstaChegando.close();
                    //modoTexto();
                    modoReceptorArquivo = false;
                    JOptionPane.showMessageDialog(null, "O arquivo foi recebido.\nPor favor abra uma nova janela para iniciar uma nova conversa.");
                }
            } catch (IOException ex) {
                JOptionPane.showConfirmDialog(null, ex.getMessage());
            }
        }
    }

    private void tryMsg(String msg) {
        if (msg.startsWith("MESSAGE")) {
            String body = msg.substring("MESSAGE".length() + 1);
            vetor = body.split(":");
            jTextArea1.append(vetor[0] + " falou: " + vetor[1] + "\n");
            output.println("REPLY_MESSAGE");
            output.flush();
        } else if (msg.equals("REPLY_MESSAGE")) {
            jTextArea1.append("Sua mensagem foi entregue.\n");
        } else if (msg.startsWith("FILE")) {
            try {
                String body = msg.substring("FILE".length() + 1);
                vetor = body.split(":");
                nomeArq = vetor[0];
                transmissor = vetor[1];
                arquivoQueEstaChegando = new FileOutputStream(System.getProperty("user.home") + "/" + nomeArq);
                modoReceptorArquivo = Boolean.TRUE;
                modoArquivo();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(UsuarioChat.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void modoArquivo() {
        jTextField1.setEnabled(Boolean.FALSE);
        jButton2.setEnabled(Boolean.FALSE);
    }

    private void modoTexto() {
        jTextField1.setEnabled(Boolean.TRUE);
        jButton2.setEnabled(Boolean.TRUE);
    }
}
